package com.adlotto2.android.cronos.c2dm;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.adlotto2.android.cronos.http.CNLottoAdApiSet;
import com.adlotto2.android.util.ApplicationUtils;
import com.adlotto2.android.util.LottoAdConstants;

/**-
 * C2DM Receiver
 */
public class C2DMReceiver extends BroadcastReceiver {
	NotificationManager mNotiMgr;
	
	private String mMessage = "";
	private String mTitle = "";
	private String mAdSeq = "";
	
	private Context mContext;

    @Override
    public void onReceive(Context context, Intent intent) {
    	mContext = context;
	    if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION"))
	    {
		    handleRegistration(context, intent);
		    Log.i("C2DMReceiver","Registration ID received!!");
	    }
	    else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE"))
	    {
	    	handleMessage(context, intent);
	    	Log.i("C2DMReceiver","Push Message received!!");
	    }
    }
    
    private void handleMessage(final Context context, Intent intent) 
    {
    	/* Log.e("###############", "handleMessage");
    	 
         String title = intent.getStringExtra("title"); 
         String msg = intent.getStringExtra("msg");
         String type = intent.getStringExtra("type");
         String sendSeq = null;
         
         if(type.equals("0"))
        	 sendSeq = intent.getStringExtra("sendSeq");
         
         Log.d("handleMessage","title ==============>" + title);
         Log.d("handleMessage","msg ==============>" + msg);
         Log.d("handleMessage","type ==============>" + type);
         Log.d("handleMessage","sendSeq ==============>" + sendSeq);
         
         PushWakeLock.acquireCpuWakeLock(context);
  
         Intent i = new Intent(context, ShowMsg.class);
         Bundle b = new Bundle();
         b.putString("title", title);
         b.putString("msg", msg);
         b.putString("type", type);
         if(sendSeq != null && sendSeq.length() > 0){
        	 b.putString("sendSeq", sendSeq);
         }
         i.putExtras(b);
         i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         context.startActivity(i);*/
    	
    	/*String msg = intent.getStringExtra("msg");
    	try {
    		mGCMMessage = URLDecoder.decode(msg, "utf-8");
    	} catch(Exception e) {
    		e.printStackTrace();
    	}
    	
    	
//    	showMsg();
    	
    	
    	
    	String msg = intent.getStringExtra("msg");
    	try {
    		msg = URLDecoder.decode(msg, "utf-8");
    	} catch(Exception e) {
    		e.printStackTrace();
    	}
    	
    	// JSON 파싱!!
    	if(parseJson(msg)) {
    		PushWakeLock.acquireCpuWakeLock(context);
    		new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					PushWakeLock.releaseCpuLock();
				}
    			
    		}, 2000);
    		
            Intent i = new Intent(context, ShowMsg.class);
            Bundle b = new Bundle();
            b.putString("title", mTitle);
            b.putString("msg", mMessage);
            b.putString("type", "0");
            b.putString("sendSeq", mAdSeq);
            
            i.putExtras(b);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        	
        	
        	
        	

        	NotificationManager notificationManager = (NotificationManager)context.getSystemService(Activity.NOTIFICATION_SERVICE);

        	// 해당 어플을 실행하는 이벤트를 하고싶을 때 아래 주석을 풀어주세요
        	// PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, 
        	// new Intent(context, 어플이 처음 시작되는 클래스명.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0);
        	Intent mainIntent = new Intent(context, LottoAdFullActivity.class);
    		mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
                    | Intent.FLAG_ACTIVITY_CLEAR_TOP 
                    | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    		mainIntent.putExtra("sendSeq", mAdSeq);
        	
        	PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);
        	
        	 Notification noti = new NotificationCompat.Builder(context)
             .setContentTitle(mTitle)
             .setContentText(mMessage)
             .setContentIntent(pendingIntent)
             .setSmallIcon(R.drawable.icon1_2)
             .setAutoCancel(true)
             .setVibrate(new long[] { 500, 100, 500, 100 })
             .build();
        	 notificationManager.notify(0, noti);
        	
        	

        	/*Notification notification = new Notification(R.drawable.icon1_2, title, System.currentTimeMillis());
        	notification.tickerText = ticker;
        	notification.when = System.currentTimeMillis();
        	notification.vibrate = new long[] { 500, 100, 500, 100 };
        	notification.defaults |= Notification.DEFAULT_SOUND;
        	notification.defaults |= Notification.DEFAULT_VIBRATE;
        	notification.flags = Notification.FLAG_AUTO_CANCEL;
        	notification.setLatestEventInfo(context, title, mGCMMessage, pendingIntent);
        	notificationManager.notify(0, noti);*/
        	
        	
        	
        	/*NotificationManager manager = (NotificationManager) context
    				.getSystemService(Context.NOTIFICATION_SERVICE);

    		Intent sendIntent = new Intent(context.getApplicationContext(),
    				NotificationHandlerActivity.class);
    		sendIntent.putExtra("type", noti_type);
    		sendIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    		sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    		PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
    				sendIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    		
    		Notification noti = new Notification(R.drawable.ic_launcher,
    				noti_title, System.currentTimeMillis());
    		noti.defaults |= Notification.DEFAULT_SOUND;
    		noti.flags = Notification.FLAG_AUTO_CANCEL;
    		noti.setLatestEventInfo(context, noti_title,
    				noti_message, contentIntent);
    		manager.notify(KPNS_NOTIFICATION_ID, noti);*/
    	
    	
        
    }
    
    private boolean parseJson(String str) {
    	if(str == null || str.equals("")) {
    		return false;
    	}
    	
    	JSONObject obj = null;
    	try {
    		obj = new JSONObject(str);
    		mTitle = obj.getString("title");
    		mMessage = obj.getString("message");
    		mAdSeq = obj.getString("adSeq");
    		
    		if(!CNLottoAdApiSet.isLive()) {
    			Log.i("BenTag", "parsed text \nTitle : " + mTitle + "\nMessage : " + mMessage + "\nAdSequence : " + mAdSeq);
    		}
    		
    		
    		return true;
    		
    	} catch(JSONException e) {
    		e.printStackTrace();
    		return false;
    	}
    }
    
    private void handleRegistration(Context context, Intent intent) 
	{
    	String mRegistrationId = intent.getStringExtra("registration_id");
    	Log.d("BenTag","mRegistrationId : "+mRegistrationId);
		if (intent.getStringExtra("error") != null){
			
			String error = intent.getStringExtra("error");
			if (error == "SERVICE_NOT_AVAILABLE") 
			{
			} else if (error == "ACCOUNT_MISSING") 
			{
			} else if (error == "AUTHENTICATION_FAILED") 
			{
			} else if (error == "TOO_MANY_REGISTRATIONS") 
			{
			} else if (error == "INVALID_SENDER") 
			{
			} else if (error == "PHONE_REGISTRATION_ERROR") 
			{
			}
		} 
		else if (intent.getStringExtra("unregistered") != null){
		}else if (mRegistrationId != null){
						
			ApplicationUtils.setStrPreferences(context, LottoAdConstants.PREFER_REGISTRATION_ID, mRegistrationId);
			
		}
	}
}